<template>
  <div class="controls">
    <el-button @click="exportBpmn">导出BPMN文件</el-button>
    <el-button @click="showDeployDialog" type="primary">保存并发布流程</el-button>
  </div>
  <div class="gradient-divider"></div>
  <div class="container">
    <div class="canvas" ref="canvasRef"></div>
    <div id="js-properties-panel" class="panel"></div>
  </div>
  <el-dialog title="部署流程" width="40%" :before-close="handleClose" v-model="isShowDeployDialog">
    <el-form :model="formData" :rules="rules" label-width="100px">
      <el-col :span="48">
        <el-form-item label="流程名" prop="processName">
          <el-input v-model="formData.processName" placeholder="请输入流程名" clearable/>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item>
          <el-steps style="width: 100%" :active="active" finish-status="success" v-if="isDeploy">
            <el-step title="正在导出bpmn流程文件"/>
            <el-step :title="step2Title"/>
            <el-step title="完成"/>
          </el-steps>
        </el-form-item>
      </el-col>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isShowDeployDialog = false">返回</el-button>
        <el-button type="success" @click="deployProcessAction">
          发布
        </el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import {xmlStr} from '@/utils/workflow/xmlStr.js';
import propertiesPanelModule from 'bpmn-js-properties-panel';
import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda';
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda';
import {customTranslate} from "@/utils/workflow/translations.js";
// 接口
import {deployProcess} from "@/api/workflow/processManager.js"
import {ElMessage, ElMessageBox} from "element-plus";

const formData = ref({
  processName: undefined
})
const rules = {
  processName: [
    {
      required: true,
      message: '请输入流程名',
      trigger: 'blur'
    }
  ]
}
// 生命周期钩子
onMounted(() => {
  console.log("组件已挂载，开始初始化模型器");
  initModeler();
});

// 组件销毁前清理
onBeforeUnmount(() => {
  if (bpmnModeler.value) {
    bpmnModeler.value.destroy();
    bpmnModeler.value = null;
  }
});

// 定义响应式变量
const canvasRef = ref(null);
const bpmnModeler = ref(null);

// 初始化模型器
const initModeler = () => {
  // 检查 canvasRef 是否存在
  if (!canvasRef.value) {
    console.error("Canvas 元素未找到，无法初始化模型器");
    return;
  }

  // 汉化模块
  const translateModule = {
    translate: ['value', customTranslate]
  };

  // 创建模型器实例
  bpmnModeler.value = new BpmnModeler({
    container: canvasRef.value,
    propertiesPanel: {parent: '#js-properties-panel'},
    additionalModules: [
      propertiesPanelModule,
      propertiesProviderModule,
      // translateModule
    ],
    moddleExtensions: {camunda: camundaModdleDescriptor}
  });

  // 导入初始 XML
  bpmnModeler.value.importXML(xmlStr, (err) => {
    if (err) {
      console.error('初始化失败:', err);
    } else {
      console.log('流程图初始化成功');
    }
  });
};

// 导出 BPMN 文件
const exportBpmn = () => {
  if (!bpmnModeler.value) {
    console.error("模型器未初始化，无法导出");
    return;
  }

  bpmnModeler.value.saveXML({format: true}, (err, xml) => {
    if (err) {
      console.error('导出失败:', err);
      return;
    }

    // 创建下载链接
    const blob = new Blob([xml], {type: 'application/bpmn20-xml'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');

    a.href = url;
    a.download = 'process.bpmn';
    document.body.appendChild(a);
    a.click();

    // 清理资源
    URL.revokeObjectURL(url);
    a.remove();
    console.log('导出成功:', xml);
  });
};

// 保存并发布至新流程
const isShowDeployDialog = ref(false)
const showDeployDialog = () => {
  isShowDeployDialog.value = true
}

const isDeploy = ref(false)
const active = ref(0)
const step2Title = ref("")
const deployProcessAction = async () => {
  if (!formData.value.processName) {
    ElMessage.error('请输入流程名');
    return;
  }
  step2Title.value = "正在部署{ " + formData.value.processName + " }流程";
  isDeploy.value = true;
  // 步骤1：导出BPMN
  if (!bpmnModeler.value) {
    console.error("模型器未初始化，无法导出");
    return;
  }
  let xmlContent;
  await new Promise((resolve, reject) => {
    bpmnModeler.value.saveXML({format: true}, (err, xml) => {
      if (err) return reject(err);
      xmlContent = xml;
      resolve(xml);
    });
  });
  active.value += 1;
  await new Promise(resolve => setTimeout(resolve, 3000));

  // 步骤2：准备参数
  const deployData = {
    processName: formData.value.processName,
    bpmnXml: xmlContent
  };
  active.value += 1;
  await new Promise(resolve => setTimeout(resolve, 3000));

  // 步骤3：调用接口
  await deployProcess(deployData).then(res => {
    if (res.code === 200) {
      ElMessage.success('流程发布成功！');
      active.value += 1;
      new Promise(resolve => setTimeout(resolve, 3000));
      isShowDeployDialog.value = false;
    } else {
      ElMessage.error('流程发布失败！');
    }
  })
};
const handleClose = () => {
  ElMessageBox.confirm('确认是否关闭?')
      .then(() => {
        isDeploy.value = false;
        active.value = 0;
        formData.value.processName = null;
        isShowDeployDialog.value = false;
      })
      .catch(() => {
        // catch error
      })
}

</script>

<style scoped>
.controls {
  padding: 1rem;
  text-align: left;
}

.container {
  width: 100%;
  height: 1000px;
  position: relative;
}

.canvas {
  width: 100%;
  height: 100%;
  background: white;
}

.panel {
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
}

/* 在<style scoped>中添加 */
.gradient-divider {
  width: 100%;
  height: 2px;
  background: #bfbfbf;
  margin: 2px 0;
}

</style>
